<?php

abstract class Json {

  /**
   * Decodes a JSON string.
   * Takes a JSON encoded string and converts it into a PHP variable.
   * @param String $string The json string being decoded.
   * @param Boolean $associative When true, returned objects will be converted into associative array.
   * @return object Returns an object or if the optional $associative parameter is true, an associative array is instead returned.
   * @link http://fr.php.net/manual/en/function.json-decode.php
   */
  public static function decode(IString $string, Boolean $associative = null) {
    return $associative == null ? json_decode($string, false) : json_decode($string, $associative->booleanValue());
  }

  /**
   * Returns the JSON representation of a value.<br />
   * Returns a string containing the JSON representation of value.
   * @param array $Object The value being encoded.<br />
   * Can be any type except a resource.<br />
   * This function only works with UTF-8 encoded data.
   * @return String Returns a JSON encoded string on success.
   * @link http://fr.php.net/manual/en/function.json-encode.php
   */
  public static function encode(array $array) {
    return new String(json_encode($array));
  }

  /**
   * Returns the last error occurred if your PHP version implements the method.
   * @return String The last error occurred.
   * @link http://fr.php.net/manual/en/function.json-last-error.php<br />
   * @throws BeObjectException
   */
  public static function getLastError() {
    $error = String::EMPTY_STRING;

    switch (Json::getLastErrorCode()) {
      case JSON_ERROR_NONE :
        $error = "No error has occured";
      case JSON_ERROR_DEPTH :
        $error = "The maximum stack depth has been exceeded";
      case JSON_ERROR_CTRL_CHAR :
        $error = "Control character error, possibly incorrectly encoded";
      case JSON_ERROR_SYNTAX :
        $error = "Syntax error";
    }
    return new String($error);
  }

  /**
   * Returns the last error code occured if your PHP version implements the method.
   * @return const The last error code.
   * @link http://fr.php.net/manual/en/function.json-last-error.php<br />
   * @throws BeObjectException
   */
  public static function getLastErrorCode() {
    if (function_exists("json_last_error")) {
      return json_last_error();
    } else {
      throw new BeObjectException("Your version of PHP does not support the 'json_last_error' method");
    }
  }

  /**
   * Defines if the called methods raised an error or not.
   * @return Boolean Returns false if no error were raised, true otherwise.
   * @link http://fr.php.net/manual/en/function.json-last-error.php<br />
   * @throws BeObjectException
   */
  public static function hasError() {
    switch (Json::getLastError()) {
      case JSON_ERROR_NONE :
        return new Boolean(false);
      default :
        return new Boolean(true);
    }
  }

}

?>
